package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.turn.OrderDetail;
import com.ruoyi.system.domain.turn.TurnInvoiceRecords;
import com.ruoyi.system.domain.turn.TurnProvideRecords;
import com.ruoyi.system.service.impl.*;
import com.ruoyi.system.util.MapperUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("system/order")
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private InvoiceRecordsServiceImpl invoiceRecordsService;
    @Autowired
    private InvoiceGroupServiceImpl invoiceGroupService;
    @Autowired
    private ProvideRecordsServiceImpl provideRecordsService;
    @Autowired
    private ProvideInfoServiceImpl provideInfoService;
    @Autowired
    private SysDeptServiceImpl sysDeptService;
    @Autowired
    private ProvideAllRecordsServiceImpl provideAllRecordsService;
    @Autowired
    private ProvideWareServiceImpl provideWareService;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private InvoiceRecordsAuditServiceImpl invoiceRecordsAuditService;
    @Autowired
    private SysAuditServiceImpl sysAuditService;
    @Autowired
    private ProductInfoServiceImpl productInfoService;
    @Autowired
    private OrderServiceImpl orderService;



    /**
     * 自动接入配件库数据
     */

    @GetMapping("/getMonthlyStorageOut")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> getMonthlyStorageOut(@RequestParam("createTime") String createTime) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();


        // 请求参数
        Map<String, String> requestBody = Collections.singletonMap("createTime", createTime);
        Map<String, String> inRequestBody = Collections.singletonMap("createTime", createTime);

        // 发送 POST 请求获取数据
        Map<String, Object> body = getRequestData("http://203.156.246.189:13925/warehousePDA/monthStorageOut", requestBody);
        Map<String, Object> inBody = getRequestData("http://203.156.246.189:13925/warehousePDA/monthStorageIn", inRequestBody);

        // 判断请求结果
        validateResponse(body, inBody,createTime);

        // 解析数据
        List<TurnProvideRecords> turnProvideRecordsList = parseOrderData(body);
        List<TurnProvideRecords> turnProvideRecordsList1 = parseOrderData(inBody);

        // 合并数据
        List<TurnProvideRecords> combinedList = new ArrayList<>(turnProvideRecordsList);
        combinedList.addAll(turnProvideRecordsList1);

        // 批量新增的集合
        List<ProvideRecords> provideRecordsList = createProvideRecordsList(combinedList, createTime);
        provideRecordsService.insertBatch(provideRecordsList);

        // 添加配件类型
        addInvoiceGroups();

        // 添加配件总表计算
        calculateProvideAllRecords(createTime);

        // 修改配件总表财务编码
        updateProvideAllRecordsFinanceCode(createTime);
        returnMap.put("code",200);
        returnMap.put("msg","数据接入成功！");
        returnMap.put("data",provideRecordsList);
        return ResponseEntity.ok(returnMap);
    }



    /**
     * 自动接入中心库数据
     */
    @GetMapping("/zxkMonthStorageIn")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> zxkMonthStorageIn(@RequestParam("createTime") String createTime) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();


        // 请求参数
        Map<String, String> requestBody = Collections.singletonMap("createTime", createTime);
        Map<String, String> inRequestBody = Collections.singletonMap("createTime", createTime);

        // 发送 POST 请求获取数据
        Map<String, Object> body = getRequestData("http://203.156.246.189:13925/warehousePDA/zxkMonthStorageOut", requestBody);
        Map<String, Object> inBody = getRequestData("http://203.156.246.189:13925/warehousePDA/zxkMonthStorageIn", inRequestBody);

        // 判断请求结果
        validateInvoiceResponse(body, inBody,createTime);

        // 解析数据
        List<TurnInvoiceRecords> turnProvideRecordsList = parseInvoiceData(body);
        List<TurnInvoiceRecords> turnProvideRecordsList1 = parseInvoiceData(inBody);

        // 合并数据
        List<TurnInvoiceRecords> combinedList = new ArrayList<>(turnProvideRecordsList);
        combinedList.addAll(turnProvideRecordsList1);
        for (TurnInvoiceRecords turnInvoiceRecords:combinedList) {
            InvoiceRecords invoiceRecords = new InvoiceRecords();
            SysAudit sysAudit = new SysAudit();
            sysAudit.setProductCode(turnInvoiceRecords.getProductCode());
            List<SysAudit> sysAudits = sysAuditService.selectSysAuditList(sysAudit);
            if (sysAudits == null || sysAudits.size() == 0) {
                invoiceRecords.setProductCode(turnInvoiceRecords.getProductCode());
                invoiceRecords.setProductName(turnInvoiceRecords.getProductName());
                invoiceRecords.setModel(turnInvoiceRecords.getModel());
                invoiceRecords.setSpecs(turnInvoiceRecords.getSpec());
                if (turnInvoiceRecords.getBalanceMode().equals("1")) {
                    invoiceRecords.setSettlementMode("压库");
                } else if (turnInvoiceRecords.getBalanceMode().equals("2")) {
                    invoiceRecords.setSettlementMode("买断");
                }
                invoiceRecords.setProductBrand(turnInvoiceRecords.getProductBrand());
                String provide = turnInvoiceRecords.getName();
                //判断是否存在供应商账号
                SysDept sysDept = sysDeptService.selectDeptByName(provide);
                invoiceRecords.setProvide(turnInvoiceRecords.getName());
                if (sysDept != null) {
                    invoiceRecords.setProvide(turnInvoiceRecords.getName());
                } else {
                    throw new IOException("有不存在的供应商账号-" + provide + "请先添加账号再导入！");
                }
                //判断是否在产品表中
                /*ProductInfo productInfo = new ProductInfo();
                productInfo.setProductCode(turnInvoiceRecords.getProductCode());
                List<ProductInfo> productInfos = productInfoService.selectProductInfoList(productInfo);
                if (productInfos != null && productInfos.size()>0 ) {

                } else {
                    throw new IOException("有不存在的产品编号-" + productInfo.getProductCode() + "请先在产品明细添加产品再导入！");
                }*/

                invoiceRecords.setProductCount(turnInvoiceRecords.getProductCount());
                invoiceRecords.setProductPrice(turnInvoiceRecords.getProductPrice());
                invoiceRecords.setPlarnPrice(turnInvoiceRecords.getActualPrice());
                String company = turnInvoiceRecords.getCompany();
                invoiceRecords.setCompany(company);
                invoiceRecords.setCreateTime(createTime);
                DecimalFormat df = new DecimalFormat("0.00##");
                invoiceRecords.setProductMoney(df.format(Double.valueOf(turnInvoiceRecords.getActualPrice()) * Double.valueOf(turnInvoiceRecords.getProductCount())));
                invoiceRecords.setStatus("0");
                invoiceRecordsService.insertInvoiceRecords(invoiceRecords);
            } else {
                InvoiceRecordsAudit invoiceRecordsAudit = new InvoiceRecordsAudit();
                invoiceRecordsAudit.setProductCode(turnInvoiceRecords.getProductCode());
                invoiceRecordsAudit.setProductName(turnInvoiceRecords.getProductName());
                invoiceRecordsAudit.setModel(turnInvoiceRecords.getModel());
                invoiceRecordsAudit.setSpecs(turnInvoiceRecords.getSpec());
                if (turnInvoiceRecords.getBalanceMode().equals("1")) {
                    invoiceRecordsAudit.setSettlementMode("压库");
                } else if (turnInvoiceRecords.getBalanceMode().equals("2")) {
                    invoiceRecordsAudit.setSettlementMode("买断");
                }
                invoiceRecordsAudit.setProductBrand(turnInvoiceRecords.getProductBrand());
                String provide = turnInvoiceRecords.getName();
                SysDept sysDept = sysDeptService.selectDeptByName(provide);
                invoiceRecordsAudit.setProvide(turnInvoiceRecords.getName());
                if (sysDept != null) {
                    invoiceRecordsAudit.setProvide(turnInvoiceRecords.getName());
                } else {
                    throw new IOException("有不存在的供应商账号-" + provide + "请先添加账号再导入！");
                }

                //判断是否在产品表中
                /*ProductInfo productInfo = new ProductInfo();
                productInfo.setProductCode(turnInvoiceRecords.getProductCode());
                List<ProductInfo> productInfos = productInfoService.selectProductInfoList(productInfo);
                if (productInfos != null && productInfos.size()>0 ) {

                } else {
                    throw new IOException("有不存在的产品编号-" + productInfo.getProductCode() + "请先在产品明细添加产品再导入！");
                }*/

                invoiceRecordsAudit.setProductCount(turnInvoiceRecords.getProductCount());
                invoiceRecordsAudit.setProductPrice(turnInvoiceRecords.getProductPrice());
                invoiceRecordsAudit.setPlarnPrice(turnInvoiceRecords.getActualPrice());
                String company = turnInvoiceRecords.getCompany();
                invoiceRecordsAudit.setCompany(company);
                invoiceRecordsAudit.setCreateTime(createTime);
                DecimalFormat df = new DecimalFormat("0.00");
                invoiceRecordsAudit.setProductMoney(df.format(Double.valueOf(turnInvoiceRecords.getActualPrice()) * Double.valueOf(turnInvoiceRecords.getProductCount())));
                invoiceRecordsAudit.setStatus("0");
                invoiceRecordsAuditService.insertInvoiceRecordsAudit(invoiceRecordsAudit);
            }
        }
        //添加产品类型表
        List<String> list = invoiceGroupService.selectProductCode();
        List<String> list1 = invoiceRecordsService.selectProductCode(list);
        for (String str:list1) {
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(str);
            invoiceGroup.setProductGroup("配件");
            invoiceGroupService.insertInvoiceGroup(invoiceGroup);
        }

        returnMap.put("code",200);
        returnMap.put("msg","数据接入成功！");
        returnMap.put("data",combinedList);
        return ResponseEntity.ok(combinedList);
    }


    /**
     * 查询订单数据
     */
    @GetMapping("/gsOrder")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> gsOrder(@RequestParam("startTime") String startTime,@RequestParam("endTime")String endTime,
                                     @RequestParam(value = "provide",required = false,defaultValue = "")String provide,@RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize")Integer pageSize) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        // 请求参数
        Map<String, String> requestBody = new HashMap();
        requestBody.put("startTime",startTime);
        requestBody.put("endTime",endTime);
        ProvideInfo provideInfo = new ProvideInfo();
        provideInfo.setName(provide);
        List<ProvideInfo> provideInfos = provideInfoService.selectProvideInfoList(provideInfo);
        if(provideInfos!=null&&provideInfos.size()>0){
            requestBody.put("providerCode",provideInfos.get(0).getCode());
        }else{
            returnMap.put("code",500);
            returnMap.put("msg","对不起您的部门没有供应商编码 请联系管理员处理！");
            return ResponseEntity.ok(returnMap);
        }


        // 发送 POST 请求获取数据
        Map<String, Object> body = getRequestData("http://203.156.246.189:13925/warehousePDA/gsOrder", requestBody);

        // 判断请求结果
        if (!body.get("code").equals(200) ) {
            throw new IOException("Request failed with code: " + body.get("code") );
        }
        // 解析数据
        String jsonData = MapperUtils.obj2json(body.get("data"));
        Map<String, Object> map = MapperUtils.json2map(jsonData);
        String jsonOrder = MapperUtils.obj2json(map.get("order"));
        List<OrderDetail> orderDetails = new ArrayList<>();
        if(jsonOrder.equals("\"未查到数据\"")){
            returnMap.put("code",200);
            returnMap.put("msg","未查询到此供应商数据！");
            returnMap.put("data","");
            returnMap.put("total", 0);
            return ResponseEntity.ok(returnMap);
        }else{
            orderDetails = MapperUtils.json2list(jsonOrder, OrderDetail.class);
        }

        // 对列表进行分页处理
        int total = orderDetails.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        List<OrderDetail> returnList = orderDetails.subList(startIndex, endIndex);



        returnMap.put("code",200);
        returnMap.put("msg","订单查询成功！");
        returnMap.put("data",returnList);
        returnMap.put("total", total);
        return ResponseEntity.ok(returnMap);
    }



    /**
     * 接入订单数据
     */
    @Anonymous
    @RequestMapping("/insertOrder")
    @Transactional(rollbackFor = Exception.class)
    public String insertOrder(@RequestBody List<Order> orderList) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        try{
            int count = orderService.insertOrderBitchs(orderList);
            returnMap.put("code",200);
            returnMap.put("msg","推送订单成功");
        }catch (Exception e){
            returnMap.put("code",500);
            returnMap.put("msg","服务器异常 请稍后再试！");
        }
         return MapperUtils.mapToJson(returnMap);
    }

    /**
     * 查询订单数据（仓库）
     */
    @Anonymous
    @RequestMapping("/getOrder")
    @Transactional(rollbackFor = Exception.class)
    public String getOrder(@RequestParam("sendOrderId")String sendOrderId) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        List<Order> orders = orderService.selectOrderBySendId(sendOrderId);
        List datas=new ArrayList();
        for (Order orderMap : orders)
        {
            Map data=new HashMap();
            data.put("productCode",orderMap.getGsConcentricityId());
            data.put("productCount",orderMap.getActSendCount());
            data.put("qrCode","");
            datas.add(data);
        }
        if(orders!=null&&orders.size()>0) {
            returnMap.put("data", datas);
            returnMap.put("code", 200);
            returnMap.put("msg", "查询送货单成功！");
            returnMap.put("success", true);
            returnMap.put("providerName",orders.get(0).getProviderName());
            returnMap.put("providerCode",orders.get(0).getProviderCode());
        }else{
            returnMap.put("data", orders);
            returnMap.put("success", true);
            returnMap.put("code", 200);
            returnMap.put("msg", "查询送货单成功！");
        }
        return MapperUtils.mapToJson(returnMap);
    }

    /**
     * 查询订单数据（中心库）
     */
    @RequestMapping("/getZXKOrder")
    @Anonymous
    @Transactional(rollbackFor = Exception.class)
    public String getZXKOrder(@RequestParam("sendOrderId")String sendOrderId) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        List<Order> orders = orderService.selectOrderBySendId(sendOrderId);
        List datas=new ArrayList();
        for (Order orderMap : orders)
        {
            Map data=new HashMap();
            data.put("gsConcentricityId",orderMap.getGsConcentricityId());
            data.put("gsOrderCount",orderMap.getActSendCount());
            data.put("gsDeliverGoodsDate",orderMap.getGsDeliverGoodsDate());
            data.put("gsWorkcorpId",orderMap.getGsWorkcorpId());
            data.put("gsGoodsUnitprice",orderMap.getGsGoodsUnitprice());
            data.put("gsOrderContactName",orderMap.getGsOrderContactName());
            data.put("gsOrderContactPhone",orderMap.getGsOrderContactPhone());
            data.put("gsDeliverGoodsAddr",orderMap.getGsDeliverGoodsAddr());
            datas.add(data);
        }
        if(orders!=null&&orders.size()>0) {
            returnMap.put("order", datas);
            returnMap.put("code", 200);
            returnMap.put("msg", "查询送货单成功！");
            returnMap.put("success", true);
        }else{
            returnMap.put("order", orders);
            returnMap.put("success", true);
            returnMap.put("code", 200);
            returnMap.put("msg", "查询送货单成功！");
        }
        return MapperUtils.mapToJson(returnMap);
    }

    /**
     * 订单入库后返回实际入库数量以及订单编号
     * @return
     */
    @Anonymous
    @RequestMapping("/reciveOrder")
    @Transactional(rollbackFor = Exception.class)
    public String reciveOrder(@RequestBody List<Map<String,Object>> reciveList) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        try{
            for (Map<String,Object> hashMap:reciveList) {
                orderService.reciveOrder(hashMap.get("actReciveCount").toString(), hashMap.get("sendOrderId").toString(),hashMap.get("gsConcentricityId").toString());
            }
            returnMap.put("code",200);
            returnMap.put("msg","入库送货单成功");
        }catch (Exception e){
            e.printStackTrace();
            returnMap.put("code",200);
            returnMap.put("msg","入库送货单失败 请稍后再试！");
        }
        return MapperUtils.mapToJson(returnMap);
    }

    /**
     * 订单入库后红冲
     * @return
     */
    @RequestMapping("/reciveCancelOrder")
    @Transactional(rollbackFor = Exception.class)
    public String reciveCancelOrder(@RequestBody List<Map<String,Object>> reciveList) throws Exception {
        HashMap<String,Object> returnMap = new HashMap<>();
        try{
            for (Map<String,Object> hashMap:reciveList) {
                orderService.reciveCancelOrder(hashMap.get("actReciveCount").toString(), hashMap.get("sendOrderId").toString(),hashMap.get("gsConcentricityId").toString());
            }
            returnMap.put("code",200);
            returnMap.put("msg","入库送货单成功");
        }catch (Exception e){
            e.printStackTrace();
            returnMap.put("code",200);
            returnMap.put("msg","入库送货单失败 请稍后再试！");
        }
        return MapperUtils.mapToJson(returnMap);
    }


    /**
     * 前端-查询订单数据
     */
    @RequestMapping("listOrder")
    public AjaxResult listOrder(Order order,@RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize")Integer pageSize){
        Map<String, Object> result = new HashMap<>();
        List<Order> orders;
        int s =Integer.valueOf(order.getGsOrderDetailStatus());
        try{
            if(s==-1)
            {
                order.setGsOrderDetailStatus("");
                orders = orderService.listOrder(order);
            }
            else
            {
                //未完成
                if(s!=255)
                {
                    orders = orderService.listOrder(order);
                }
                else
                {
                    orders = orderService.newListOrder(order);
                }
           }

            // 对列表进行分页处理
            int total = orders.size();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            List<Order> paginatedList = orders.subList(startIndex, endIndex);
            // 返回分页结果
            result.put("list", paginatedList);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("对不起！系统错误请稍后再试");
        }
        return AjaxResult.success(result);
    }

    /**
     * 前端-查询订单数据（新）
     */
    @RequestMapping("newListOrder")
    public AjaxResult newListOrder(Order order,@RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize")Integer pageSize){
        Map<String, Object> result = new HashMap<>();

            try{
                List<Order> orders = orderService.newListOrder(order);
                // 对列表进行分页处理
                int total = orders.size();
                int startIndex = (pageNum - 1) * pageSize;
                int endIndex = Math.min(startIndex + pageSize, total);
                List<Order> paginatedList = orders.subList(startIndex, endIndex);
                // 返回分页结果
                result.put("list", paginatedList);
                result.put("total", total);
                result.put("pageNum", pageNum);
                result.put("pageSize", pageSize);
            }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.error("对不起！系统错误请稍后再试");
            }

        return AjaxResult.success(result);
    }

    /**
     * 生成送货单
     */
    @RequestMapping("createSendOrder")
    public AjaxResult createSendOrder(@RequestBody List<Map<String,Object>> sendOrderList){
        Map<String, Object> result = new HashMap<>();
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String format = sdf.format(new Date());
            String pre = "SNH";
            String sendOrderId = orderService.getSendOrderId(pre + format);
            if(sendOrderId==null){
                sendOrderId = pre+format+"001";
                for (Map<String,Object> map:sendOrderList) {
                    log.info(map.get("actSendCount").toString());
                    log.info(map.get("gsOrderTempid").toString());
                    log.info(sendOrderId);
                    orderService.updateOrderSendCount(map.get("actSendCount").toString(),map.get("gsOrderTempid").toString(),sendOrderId,map.get("gsConcentricityId").toString());
                }
            }else{
                String end = sendOrderId.substring(sendOrderId.length()-3);
                end = String.valueOf(Integer.parseInt(end)+1);
                String code = getCode(end, 3);
                for (Map<String,Object> map:sendOrderList) {
                    orderService.updateOrderSendCount(map.get("actSendCount").toString(),map.get("gsOrderTempid").toString(),pre+format+code,map.get("gsConcentricityId").toString());
                }
            }
            result.put("code",200);
            result.put("msg","生成送货单成功！");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.success("对不起！系统错误请稍后再试");
        }
        return AjaxResult.success(result);
    }


    /**
     * 生成送货单号
     */
    @RequestMapping("createNewSendOrder")
    public AjaxResult createNewSendOrder(){
        Map<String, Object> result = new HashMap<>();
        try{
            long timestamp = System.currentTimeMillis();
            Date timesDate = new Date(timestamp);
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
            int random = new Random().nextInt(9000) + 1000;
            String format = sdf.format(timesDate);
            String pre = "";
            //中心库订单区分
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            SysDept sysdept = sysUser.getDept();
            if(sysdept.getDeptName()=="物资中心库"&&sysdept.getDeptName().equals("物资中心库")||sysdept.getDeptName().equals("物资中心库（索赔）")&&sysdept.getDeptName()=="物资中心库（索赔）")
            {
                pre = "SH";
            }
            else
            {
                pre = "SNH";
            }

            String sendOrderId = pre+format+random;

            result.put("sendOrderId",sendOrderId);
            result.put("code",200);
            result.put("msg","生成送货单成功！");

        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.success("对不起！系统错误请稍后再试");
        }
        return AjaxResult.success(result);
    }

    /**
     * 打印货单
     */
    @RequestMapping("printNewSendOrder")
    public AjaxResult printNewSendOrder(@RequestBody List<Map<String,Object>> sendOrderList){
        Map<String, Object> returnMap = new HashMap<>();
        try{
            for (Map<String,Object> hashMap:sendOrderList)
            {
                orderService.printNewSendOrder(hashMap.get("id").toString(),hashMap.get("sendOrderId").toString(),hashMap.get("actSendCount").toString(),hashMap.get("createTime").toString());
            }
            returnMap.put("code",200);
            returnMap.put("msg","打印送货单成功");
        }catch (Exception e){
            e.printStackTrace();
            returnMap.put("code",500);
            return AjaxResult.success("对不起！系统错误请稍后再试");
        }
        return AjaxResult.success(returnMap);
    }

    /**
     * 供应商取消订单
     * @return
     */
    @RequestMapping("/cancelOrder")
    public AjaxResult cancelOrder(@RequestBody List<Map<String,Object>> cancelOrderList){
        Map<String, Object> returnMap = new HashMap<>();
        try{
            for (Map<String,Object> hashMap:cancelOrderList) {
                orderService.cancelOrder(hashMap.get("gsOrderTempid").toString(),hashMap.get("gsConcentricityId").toString());
            }
            returnMap.put("code",200);
            returnMap.put("msg","取消订单成功");
        }catch (Exception e){
            e.printStackTrace();
            returnMap.put("code",500);
            returnMap.put("msg","取消订单失败 请稍后再试！");
        }
        return AjaxResult.success(returnMap);
    }

    /**
     * 通过送货单查询
     */
    @RequestMapping("searchSendOrder")
    public AjaxResult searchSendOrder(@RequestParam("sendOrderId")String sendOrderId){
        Map<String, Object> result = new HashMap<>();
        try{
            List<Order> orders = orderService.searchSendOrder(sendOrderId);

            result.put("list", orders);
            result.put("code",200);
            result.put("msg","送货单查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("对不起！系统错误请稍后再试");
        }
        return AjaxResult.success(result);
    }


































    private String getCode(String s, int size) {
        String code = "";
        int length = size - s.length();
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                code = code + "0";
            }
        }
        return code + s;
    }

    private Map<String, Object> getRequestData(String url, Map<String, String> requestBody) {
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, requestBody, Map.class);
        return responseEntity.getBody();
    }

    private void validateResponse(Map<String, Object> body, Map<String, Object> inBody,String createTime) throws IOException {
        if (!body.get("code").equals(200) || !inBody.get("code").equals(200)) {
            throw new IOException("Request failed with code: " + body.get("code") + " and " + inBody.get("code"));
        }else {
            provideRecordsService.deleteUpload(createTime);
            provideAllRecordsService.deleteUpload(createTime);
        }
    }

    private void validateInvoiceResponse(Map<String, Object> body, Map<String, Object> inBody,String createTime) throws IOException {
        if (!body.get("code").equals(200) || !inBody.get("code").equals(200)) {
            throw new IOException("Request failed with code: " + body.get("code") + " and " + inBody.get("code"));
        }else {
            invoiceRecordsService.deleteUpload(createTime);
            invoiceRecordsAuditService.deleteUpload(createTime);
        }
    }

    @SneakyThrows
    private List<TurnProvideRecords> parseOrderData(Map<String, Object> responseBody) {
        String jsonData = MapperUtils.obj2json(responseBody.get("data"));
        Map<String, Object> map = MapperUtils.json2map(jsonData);
        String jsonOrder = MapperUtils.obj2json(map.get("order"));
        return MapperUtils.json2list(jsonOrder, TurnProvideRecords.class);
    }

    @SneakyThrows
    private List<TurnInvoiceRecords> parseInvoiceData(Map<String, Object> responseBody) {
        String jsonData = MapperUtils.obj2json(responseBody.get("data"));
        Map<String, Object> map = MapperUtils.json2map(jsonData);
        String jsonOrder = MapperUtils.obj2json(map.get("order"));
        return MapperUtils.json2list(jsonOrder, TurnInvoiceRecords.class);
    }

    private List<ProvideRecords> createProvideRecordsList(List<TurnProvideRecords> turnProvideRecordsList, String createTime) throws IOException {
        List<ProvideRecords> provideRecordsList = new ArrayList<>();
        for (TurnProvideRecords turnProvideRecords : turnProvideRecordsList) {
            ProvideRecords provideRecords = new ProvideRecords();
            validateWarehouseCode(turnProvideRecords, provideRecords);
            populateProvideRecords(provideRecords, turnProvideRecords, createTime);
            //判断是否在产品表中
           /* ProductInfo productInfo = new ProductInfo();
            productInfo.setProductCode(turnProvideRecords.getProductCode());
            List<ProductInfo> productInfos = productInfoService.selectProductInfoList(productInfo);
            if (productInfos != null && productInfos.size()>0 ) {

            } else {
                throw new IOException("有不存在的产品编号-" + productInfo.getProductCode() + "请先在产品明细添加产品再导入！");
            }*/
            provideRecordsList.add(provideRecords);
        }
        return provideRecordsList;
    }

    private void validateWarehouseCode(TurnProvideRecords turnProvideRecords, ProvideRecords provideRecords) throws IOException {
        String wareHouseCode = turnProvideRecords.getWarehouseCode();
        ProvideWare provideWare = new ProvideWare();
        if (wareHouseCode != null && wareHouseCode.length() == 8 && wareHouseCode.endsWith("00")) {
            provideWare.setWareCode(wareHouseCode.substring(0, 6));
        } else {
            provideWare.setWareCode(wareHouseCode);
        }
        List<ProvideWare> provideWares = provideWareService.selectProvideWareList(provideWare);
        if (provideWares != null && !provideWares.isEmpty()) {
            provideRecords.setWarehouseCode(wareHouseCode);
        } else {
            throw new IOException("有不存在的仓库-" + turnProvideRecords.getWarehouseName() + " 请先添加仓库后再导入！");
        }
    }

    private void populateProvideRecords(ProvideRecords provideRecords, TurnProvideRecords turnProvideRecords, String createTime) throws IOException {
        provideRecords.setWarehouseName(turnProvideRecords.getWarehouseName());
        provideRecords.setProductCode(turnProvideRecords.getProductCode());
        provideRecords.setProductName(turnProvideRecords.getProductName());
        provideRecords.setProductPrice(turnProvideRecords.getProductPrice());
        provideRecords.setPlarnPrice(turnProvideRecords.getActualPrice());
        provideRecords.setModel(turnProvideRecords.getModel());
        provideRecords.setSpecs(turnProvideRecords.getSpec());
        provideRecords.setProductBrand(turnProvideRecords.getProductBrand());
        String provide = turnProvideRecords.getName();
        SysDept sysDept = sysDeptService.selectDeptByName(provide);
        if (sysDept != null) {
            provideRecords.setProvide(provide);
        } else {
            throw new IOException("有不存在的供应商账号-" + provide + "请先添加账号再导入！");
        }
        provideRecords.setProductCount(turnProvideRecords.getProductCount());
        provideRecords.setSettlementMode(turnProvideRecords.getBalanceMode().equals("1") ? "压库" : "买断");
        provideRecords.setCreateTime(createTime);
        DecimalFormat df = new DecimalFormat("0.00##");
        provideRecords.setProductMoney(df.format(Double.valueOf(turnProvideRecords.getActualPrice()) * Double.valueOf(turnProvideRecords.getProductCount())));
        provideRecords.setStatus("0");
    }

    private void addInvoiceGroups() {
        List<String> productCodes = invoiceGroupService.selectProductCode();
        List<String> existingProductCodes = provideRecordsService.selectProductCode(productCodes);
        // 将现有的产品编码转换为 InvoiceGroup 对象列表
        List<InvoiceGroup> newInvoiceGroups = existingProductCodes.stream()
                .map(code -> {
                    InvoiceGroup invoiceGroup = new InvoiceGroup();
                    invoiceGroup.setProductCode(code);
                    invoiceGroup.setProductGroup("配件");
                    return invoiceGroup;
                })
                .collect(Collectors.toList());
        if (!newInvoiceGroups.isEmpty()) {
            invoiceGroupService.insertInvoiceGroups(newInvoiceGroups);
        }
    }

    private void calculateProvideAllRecords(String createTime) {
        List<Map<String, Object>> maps = provideAllRecordsService.selectAllRecords(createTime);
        if (maps != null && !maps.isEmpty()) {
            DecimalFormat df = new DecimalFormat("0.00##");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = sdf.format(new Date());
            List<ProvideAllRecords> provideAllRecordsList = maps.stream()
                    .map(map -> {
                        ProvideAllRecords provideAllRecords = new ProvideAllRecords();
                        provideAllRecords.setProvide(map.get("provide").toString());
                        provideAllRecords.setCreateTime(map.get("create_time").toString());
                        provideAllRecords.setFinanceCode("");
                        provideAllRecords.setTaxRed("0");
                        provideAllRecords.setActMoney("0");
                        provideAllRecords.setPlatformMoney(df.format(Double.valueOf(map.get("priceMoney").toString())));
                        provideAllRecords.setPayableMoney(df.format(Double.valueOf(map.get("money").toString())));
                        provideAllRecords.setUnpaidMoney(df.format(Double.valueOf(map.get("money").toString())));
                        provideAllRecords.setValuationTax("0");
                        provideAllRecords.setUpdateTime(updateTime);
                        provideAllRecords.setStatus("0");
                        return provideAllRecords;
                    })
                    .collect(Collectors.toList());
            provideAllRecordsService.insertBatch(provideAllRecordsList);
        }
    }

    private void updateProvideAllRecordsFinanceCode(String createTime) {
        ProvideAllRecords provideAll = new ProvideAllRecords();
        provideAll.setCreateTime(createTime);
        List<ProvideAllRecords> provideAllRecords = provideAllRecordsService.selectProvideAllRecordsList(provideAll);
        List<ProvideInfo> provideInfos = provideInfoService.selectProvideInfoList(new ProvideInfo());
        for (ProvideAllRecords provideAllRecords1 : provideAllRecords) {
            for (ProvideInfo provideInfo : provideInfos) {
                if (provideAllRecords1.getProvide().equals(provideInfo.getName())) {
                    provideAllRecords1.setFinanceCode(provideInfo.getFinanceCode());
                    provideAllRecordsService.updateProvideAllRecords(provideAllRecords1);
                }
            }
        }
    }


}
